package com.mini.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mini.admin.api.entity.SysPermission;
import com.mini.admin.mapper.SysPermissionMapper;
import com.mini.admin.service.SysPermissionService;
import com.mini.common.core.constant.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Zhou Feng
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取全部权限和角色的对应的关系
     */
    @Override
    public List<SysPermission> getAllPermRoles() {
        return this.baseMapper.getAllPermRoles();
    }

    /**
     * 刷新redis中的 权限-角色 缓存
     */
    @Override
    public void refreshPermRoles() {
        List<SysPermission> perms = this.getAllPermRoles();
        HashMap<String, List<String>> urlRoles = new HashMap<>();
        Optional.ofNullable(perms)
                .orElseGet(ArrayList::new)
                .stream()
                .filter(permRoles -> StrUtil.isNotBlank(permRoles.getUrlPerm()))
                .forEach(permRoles -> {
                    //合并重复的权限的角色
                    List<String> oldUrlRoles = urlRoles.getOrDefault(permRoles.getUrlPerm(), new ArrayList<>());
                    oldUrlRoles.addAll(permRoles.getRoles());
                    List<String> collect = oldUrlRoles.stream().distinct().collect(Collectors.toList());
                    urlRoles.put(permRoles.getUrlPerm(), collect);
                });
        redisTemplate.opsForHash().putAll(RedisConstants.URL_PERM_ROLES_KEY, urlRoles);
    }
}




